﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.WebControls;
using SharePoint911.SPAXO.Properties;

namespace SharePoint911.SPAXO
{
    [CLSCompliant(false)]
    public class SpaxoConfig : GlobalAdminPageBase
    {
        protected Literal ErrorMessageLiteral;
        protected WebApplicationSelector WebAppSelector;
        protected DropDownList InjectionOptionInput;
        protected Button SaveSettings;

        private void SetupPageElements()
        {
            SPWebApplication webApp = this.WebAppSelector.CurrentItem;

            if (webApp != null)
            {
                //Get the settings
                ConfigSettings settings = SpaxoGlobal.GetSettings(webApp);

                //Check to see if the setting exist
                if (settings == null)
                {
                    //Specify Defaults if any
                    this.InjectionOptionInput.Items.FindByValue("Head").Selected = true;
                }
                else
                {
                    //Get values for the page
                    this.InjectionOptionInput.Items.FindByValue(settings.InjectionOption).Selected = true;
                }
            }
        }

        protected void WebAppSelector_ContextChange(object sender, EventArgs e)
        {
            SetupPageElements();
        }

        protected void SaveSettings_OnClick (object sender, EventArgs e)
        {
            SPWebApplication webApp = this.WebAppSelector.CurrentItem;

            //Get settings
            ConfigSettings settings = SpaxoGlobal.GetSettings(webApp);

            //If settings do not exist create them
            if (settings == null)
            {
                settings = SpaxoGlobal.CreateSettings(this.WebAppSelector.CurrentItem);
            }

            //Set values from the page
            settings.InjectionOption = this.InjectionOptionInput.SelectedValue;

            //Validate settings
            if (SpaxoGlobal.ValidateSettings(settings))
            {
                //If the settings are valid save them
                settings.Update();
            }
            else
            {
                //If the settings are invalid display message
                this.ErrorMessageLiteral.Text = "One or more of the configuration values are not set. All values must be specified.";
            }
        }
    }
}
